package com.xwaf.platform.web.util;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class OSSUtil {
	 
//    osswebsite: https://yxstation.oss-cn-beijing.aliyuncs.com/

	  private static final Logger logger = LoggerFactory.getLogger(OSSUtil.class);
	  
//	  private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
//	  private static String accessKeyId = "LTAIbunrjHiE6LCv";
//	  private static String accessKeySecret = "JplUJMKnCtMl4sMgbtevkjAeGD3AdZ";
//	  private static String bucketName = "hx-third";
//	  private static String filedir = "polysoft/";
	 
	  private static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
	  private static String accessKeyId = "LTAIVrykmcNc7Gxv";
	  private static String accessKeySecret = "fQkUARpDbq5DNVcxjKmY68KTsiba6R";
	  private static String bucketName = "yxstation";
	  private static String filedir = "files/";
	  
	  private static OSSClient ossClient;
	 
	  public OSSUtil() {
	    ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	  }
	 
	  /**
	   * 初始化
	   */
	  public static void init() {
	    ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	  }
	 
	  /**
	   * 销毁
	   */
	  public void destory() {
	    ossClient.shutdown();
	  }
	 
	  /**
	   * 上传图片
	   *
	   * @param url
	   */
	  public void uploadImg2Oss(String url) {
	    File fileOnServer = new File(url);
	    FileInputStream fin;
	    try {
	      fin = new FileInputStream(fileOnServer);
	      String[] split = url.split("/");
	      uploadFile2OSS(fin, split[split.length - 1]);
	    } catch (FileNotFoundException e) {
	     // throw new ImgException("图片上传失败");
	    }
	  }
	 
	 
	  public String uploadImg2Oss(MultipartFile file) {
	    if (file.getSize() > 1024 * 1024) {
	     // throw new ImgException("上传图片大小不能超过1M！");
	    }
	    String originalFilename = file.getOriginalFilename();
	    String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
	    Random random = new Random();
	    String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
	    try {
	      InputStream inputStream = file.getInputStream();
	      uploadFile2OSS(inputStream, name);
	      return name;
	    } catch (Exception e) {
	   //   throw new ImgException("图片上传失败");
	    }
		return name;
	  }
	  public static String uploadImg2Oss(InputStream in,String extension) {
		  	Random random = new Random();
		    String name = null;
		    try {
		    	name =random.nextInt(10000) + System.currentTimeMillis()+random.nextInt(10000)+"."+extension;
		        String etag = uploadFile2OSS(in, name);
		        if(etag!=null && !etag.equals("")){
		        	return name;
		        }
		    } catch (Exception e) {
		   //   throw new ImgException("图片上传失败");
		    }
			return "";
		  }
	 
	  /**
	   * 获得图片路径
	   *
	   * @param fileUrl
	   * @return
	   */
	  public String getImgUrl(String fileUrl) {
	    if (!StringUtils.isEmpty(fileUrl)) {
	      String[] split = fileUrl.split("/");
	      return getUrl(filedir + split[split.length - 1]);
	    }
	    return null;
	  }
	 
	  /**
	   * 上传到OSS服务器  如果同名文件会覆盖服务器上的
	   *
	   * @param instream 文件流
	   * @param fileName 文件名称 包括后缀名
	   * @return 出错返回"" ,唯一MD5数字签名
	   */
	  public static String uploadFile2OSS(InputStream instream, String fileName) {
	    String ret = "";
	    try {
	    	init();
	      //创建上传Object的Metadata 
	      ObjectMetadata objectMetadata = new ObjectMetadata();
	      objectMetadata.setContentLength(instream.available());
	      objectMetadata.setCacheControl("no-cache");
	      objectMetadata.setHeader("Pragma", "no-cache");
	      String getcontentType = getcontentType(fileName.substring(fileName.lastIndexOf(".")));
	      if(org.apache.commons.lang3.StringUtils.isNotBlank(getcontentType)){
	    	  objectMetadata.setContentType(getcontentType);
	      }
//	      objectMetadata.setContentMD5(contentMD5);
	      objectMetadata.setContentDisposition("inline;filename=" + fileName);
	      objectMetadata.setObjectAcl(CannedAccessControlList.PublicReadWrite);//指定上传的object的访问权限为：公共读写
	      //上传文件
	      logger.info("***开始上传图片到oss服务器***"+filedir + fileName);
	      PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
	      ret = putResult.getETag();
	      logger.info("***结束上传图片到oss服务器***"+filedir + fileName+",上传结果："+ret);
	    } catch (IOException e) {
	      logger.error(e.getMessage(), e);
	    } finally {
	      try {
	        if (instream != null) {
	          instream.close();
	        }
	      } catch (IOException e) {
	        e.printStackTrace();
	      }
	    }
	    return ret;
	  }
	 
	  /**
	   * Description: 判断OSS服务文件上传时文件的contentType
	   *
	   * @param FilenameExtension 文件后缀
	   * @return String
	   */
	  public static String getcontentType(String FilenameExtension) {
	    if (FilenameExtension.equalsIgnoreCase("bmp")) {
	      return "image/bmp";
	    }
	    if (FilenameExtension.equalsIgnoreCase("gif")) {
	      return "image/gif";
	    }
	    if (FilenameExtension.equalsIgnoreCase("jpeg") ||
	        FilenameExtension.equalsIgnoreCase("jpg") ||
	        FilenameExtension.equalsIgnoreCase("png")) {
	      return "image/jpeg";
	    }
	    if (FilenameExtension.equalsIgnoreCase("html")) {
	      return "text/html";
	    }
	    if (FilenameExtension.equalsIgnoreCase("txt")) {
	      return "text/plain";
	    }
	    if (FilenameExtension.equalsIgnoreCase("vsd")) {
	      return "application/vnd.visio";
	    }
	    if (FilenameExtension.equalsIgnoreCase("pptx") ||
	        FilenameExtension.equalsIgnoreCase("ppt")) {
	      return "application/vnd.ms-powerpoint";
	    }
	    if (FilenameExtension.equalsIgnoreCase("docx") ||
	        FilenameExtension.equalsIgnoreCase("doc")) {
	      return "application/msword";
	    }
	    if (FilenameExtension.equalsIgnoreCase("xlsx") ||
		    FilenameExtension.equalsIgnoreCase("xls")) {
		      return "application/vnd.ms-excel";
		}
	    if (FilenameExtension.equalsIgnoreCase("pdf")) {
		      return "application/pdf";
		}
	    if (FilenameExtension.equalsIgnoreCase("xml")) {
	      return "text/xml";
	    }
	    if(FilenameExtension.equalsIgnoreCase("rmvb")){
	    	return "application/vnd.rn-realmedia-vbr";
		}
	    if(FilenameExtension.equalsIgnoreCase("avi")){
	    	return "video/avi";
		}
	    if (FilenameExtension.equalsIgnoreCase(".mp4")) {
			  return "video/mpeg4";
		}
	    return "";
	  }
	 
	  /**
	   * 获得url链接
	   *
	   * @param key
	   * @return
	   */
	  public static String getUrl(String key) {
	    // 设置URL过期时间为10年  3600l* 1000*24*365*10
	    Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
	    // 生成URL
	    init();
	    URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
	    if (url != null) {
	      return url.toString();
	    }
	    return null;
	  }
	    /**
	     * 获得url链接
	     * @param key
	     * @return
	     */
	    public static String url(String key){
	    	Date expires = new Date (new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
	    	GeneratePresignedUrlRequest generatePresignedUrlRequest =new GeneratePresignedUrlRequest(bucketName, key);
	    	generatePresignedUrlRequest.setExpiration(expires);
	    	init();
	    	URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
	    	return url.toString();
	    }
	    
	    /**
	     * @Description:删除文件
	     * @param key  OSS文件服务器上文件的唯一标识
	     * @ReturnType:void
	    */
	    public static void deleteFile(String key){
	    	init();
	    	ossClient.deleteObject(bucketName, filedir+key);  
	    	logger.info("删除" + bucketName + "下的文件" + filedir + key + "成功");  
	    }
	    
	    /**
	     * @Description:根据key,查询文件
	     * @param key  OSS文件服务器上文件的唯一标识
	    */
	    public static String queryFile(String key) throws Exception{
	    	init();
	    	String fileName = "";
	    	try {
				OSSObject object = ossClient.getObject(bucketName, filedir+key);
				if(object !=null){
					String[] split = object.getKey().split("/");
					fileName = split[1];
					return fileName;
				}
			} catch (OSSException e) {
				
			}
	    	return fileName;
	    }
	    
	  public static void main(String[] args) throws Exception {
//		  ossClient.getObjectMetadata(genericRequest);
		    OSSUtil os=new OSSUtil();
//		    System.out.println(os.queryFile("123.jpg"));
//		    os.deleteFile("1503554723758.doc");
			File f = new File("D:\\xxxx.jpg");
			InputStream in = new FileInputStream(f);
			String key = os.uploadImg2Oss(in,"jpg");
			System.out.println("返回："+key);
			
			//https://yxstation.oss-cn-beijing.aliyuncs.com/files/1573375813494.jpg
			
//			http://hx-third.oss-cn-hangzhou.aliyuncs.com/polysoft/1573375655865.jpg
	  }
}
